use crate::error::AppError;
use std::{
    path::Path,
    process::Command
};

pub struct CrossInstaller;

impl CrossInstaller {
    pub fn convert_elf(input: &Path, output: &Path, from_arch: &str, to_arch: &str) -> Result<(), AppError> {
        // 使用 qemu 转换二进制
        let status = Command::new("qemu-elf-convertor")
            .args(&[
                "--input", input.to_str().unwrap(),
                "--output", output.to_str().unwrap(),
                "--from", from_arch,
                "--to", to_arch
            ])
            .status()?;
        
        if !status.success() {
            Err(AppError::ArchConvertError)
        } else {
            Ok(())
        }
    }

    pub fn patch_interpreter(path: &Path, arch: &str) -> Result<(), AppError> {
        let interpreter = match arch {
            "x86_64" => "/lib/ld-linux-x86-64.so.2",
            "aarch64" => "/lib/ld-linux-aarch64.so.1",
            _ => return Err(AppError::UnsupportedArch)
        };
        
        Command::new("patchelf")
            .args(&["--set-interpreter", interpreter, path.to_str().unwrap()])
            .status()?;
        
        Ok(())
    }
}